<template>
  <div class="vote-history">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>历史投票</span>
          <el-button type="primary" @click="handleExport">导出记录</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="投票标题">
          <el-input v-model="searchForm.title" placeholder="请输入投票标题" />
        </el-form-item>
        <el-form-item label="投票类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型">
            <el-option label="宠物评选" value="pet" />
            <el-option label="活动投票" value="activity" />
            <el-option label="满意度调查" value="survey" />
          </el-select>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 历史投票列表 -->
      <el-table :data="historyList" border style="width: 100%">
        <el-table-column prop="title" label="投票标题" min-width="200" />
        <el-table-column prop="type" label="类型" width="120">
          <template #default="scope">
            <el-tag>{{ scope.row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalVotes" label="总票数" width="100" />
        <el-table-column prop="participants" label="参与人数" width="100" />
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column prop="endType" label="结束方式" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.endType === '自然结束' ? 'success' : 'warning'">
              {{ scope.row.endType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleDetail(scope.row)">
              详情
            </el-button>
            <el-button type="success" size="small" @click="handleAnalysis(scope.row)">
              分析
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 投票详情对话框 -->
    <el-dialog
      title="投票详情"
      v-model="detailDialogVisible"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="投票标题">{{ currentVote.title }}</el-descriptions-item>
        <el-descriptions-item label="投票类型">
          <el-tag>{{ currentVote.type }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ currentVote.startTime }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ currentVote.endTime }}</el-descriptions-item>
        <el-descriptions-item label="总票数">{{ currentVote.totalVotes }}</el-descriptions-item>
        <el-descriptions-item label="参与人数">{{ currentVote.participants }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">投票选项</el-divider>
      <el-table :data="currentVote.options" border style="width: 100%">
        <el-table-column label="选项图片" width="100">
          <template #default="scope">
            <el-image
              v-if="scope.row.image"
              :src="scope.row.image"
              style="width: 50px; height: 50px"
              :preview-src-list="[scope.row.image]"
            />
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="选项内容" />
        <el-table-column prop="votes" label="得票数" width="100" />
        <el-table-column label="得票率" width="120">
          <template #default="scope">
            {{ ((scope.row.votes / currentVote.totalVotes) * 100).toFixed(2) }}%
          </template>
        </el-table-column>
      </el-table>

      <el-divider content-position="left">投票趋势</el-divider>
      <div ref="chartRef" style="width: 100%; height: 300px"></div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

// 搜索表单
const searchForm = reactive({
  title: '',
  type: '',
  dateRange: []
})

// 历史投票列表数据
const historyList = ref([
  {
    id: 1,
    title: '2023年度最受欢迎宠物评选',
    type: '宠物评选',
    totalVotes: 2560,
    participants: 1280,
    startTime: '2023-12-01 00:00:00',
    endTime: '2023-12-31 23:59:59',
    endType: '自然结束',
    options: [
      { content: '金毛-Lucky', image: 'https://placeholder.com/100', votes: 1200 },
      { content: '布偶猫-Mimi', image: 'https://placeholder.com/100', votes: 800 },
      { content: '柯基-Coco', image: 'https://placeholder.com/100', votes: 560 }
    ],
    trend: [
      { date: '12-01', votes: 100 },
      { date: '12-10', votes: 800 },
      { date: '12-20', votes: 1600 },
      { date: '12-31', votes: 2560 }
    ]
  },
  {
    id: 2,
    title: '2023年第四季度服务满意度调查',
    type: '满意度调查',
    totalVotes: 520,
    participants: 520,
    startTime: '2023-12-15 00:00:00',
    endTime: '2023-12-20 23:59:59',
    endType: '手动结束',
    options: [
      { content: '非常满意', votes: 320 },
      { content: '满意', votes: 150 },
      { content: '一般', votes: 50 }
    ],
    trend: [
      { date: '12-15', votes: 100 },
      { date: '12-17', votes: 280 },
      { date: '12-19', votes: 450 },
      { date: '12-20', votes: 520 }
    ]
  }
])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 详情对话框
const detailDialogVisible = ref(false)
const currentVote = reactive({})
const chartRef = ref(null)
let chart = null

// 方法定义
const handleSearch = () => {
  ElMessage.success('搜索功能待实现')
}

const resetSearch = () => {
  searchForm.title = ''
  searchForm.type = ''
  searchForm.dateRange = []
}

const handleDetail = (row) => {
  Object.assign(currentVote, row)
  detailDialogVisible.value = true
  // 在下一个 tick 初始化图表
  setTimeout(() => {
    initChart()
  }, 0)
}

const handleAnalysis = (row) => {
  ElMessage.success('查看投票分析')
}

const handleExport = () => {
  ElMessage.success('导出功能待实现')
}

const initChart = () => {
  if (!chartRef.value) return
  
  if (chart) {
    chart.dispose()
  }
  
  chart = echarts.init(chartRef.value)
  
  const option = {
    title: {
      text: '投票趋势'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: currentVote.trend?.map(item => item.date) || []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '票数',
        type: 'line',
        smooth: true,
        data: currentVote.trend?.map(item => item.votes) || [],
        areaStyle: {}
      }
    ]
  }
  
  chart.setOption(option)
}

const handleSizeChange = (val) => {
  pageSize.value = val
  // 重新加载数据
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // 重新加载数据
}

// 组件卸载时销毁图表
onMounted(() => {
  window.addEventListener('resize', () => {
    chart?.resize()
  })
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 